package com.my.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.my.domain.ParkingSpace;
import com.my.domain.Result;
import com.my.service.ParkingSpaceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.*;

@CrossOrigin//让这个控制器支持跨域请求
@Controller
@RequestMapping("/park")
public class ParkingSpaceController {

    @Autowired
    private ParkingSpaceService parkingSpaceService;

    @Autowired
    private Map<Integer, HttpSession> sessionMap;


    @RequestMapping(path = "", method = RequestMethod.GET)
    @ResponseBody
    public List<ParkingSpace> findAll() {//查询所有车位
        return parkingSpaceService.findAll();
    }

    @RequestMapping(path = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public ParkingSpace findById(@PathVariable("id") Integer id) {//根据id查询车位
        return parkingSpaceService.findById(id);
    }


    @RequestMapping(path = "", method = RequestMethod.POST, params = {"id"})
    @ResponseBody
    public Result parking(Integer id) throws JsonProcessingException {//停车（模拟用，实际的停车由传感器触发）
        ParkingSpace parkingSpace = id > 0 ? parkingSpaceService.findById(id) : null;
        if (parkingSpace == null) {
            return Result.newErrResult("没有这个车位");
        }
        if (parkingSpace.getLocked()) {
            return Result.newErrResult(id + "号车位已被预约或占用，不能停入");
        }

        Result result = parkingSpaceService.parking(id);
        if (result.getFlag()) {
            result.setMsg("停车成功，开始计费");
        }
        return result;
    }

    @RequestMapping(path = "/cost/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Result getCost(@PathVariable("id") Integer id) {//查看实时费用
        ParkingSpace parkingSpace = id > 0 ? parkingSpaceService.findById(id) : null;
        if (parkingSpace == null) {
            return Result.newErrResult("没有这个车位");
        }
        if (!parkingSpace.getLocked()) {
            return Result.newErrResult(id + "号车位空闲，无需缴费");
        }
        if (parkingSpace.getStatus() == 2) {
            return Result.newErrResult(id + "号车位处于预约状态，无需缴费");
        }

        int money = parkingSpaceService.getCost(id);
        return Result.newResult(id + "号车位正在使用，实时费用" + money + "元", money);
    }

    @RequestMapping(path = "/cost", method = RequestMethod.POST, params = {"id", "money"})
    @ResponseBody
    public Result pay(Integer id, Integer money) {//缴费，解锁车位
        ParkingSpace parkingSpace = id > 0 ? parkingSpaceService.findById(id) : null;
        if (parkingSpace == null) {
            return Result.newErrResult("没有这个车位");
        }
        if (!parkingSpace.getLocked()) {
            return Result.newErrResult(id + "号车位空闲，无需缴费");
        }
        if (parkingSpace.getStatus() == 2) {
            return Result.newErrResult(id + "号车车位处于预约状态，无需缴费");
        }

        Result result = parkingSpaceService.pay(id, money);
        result.setMsg(result.getFlag() ? "付款成功，车位已解锁" : "付款失败，金额错误");
        return result;
    }

    //------以下是用于预约的------//
    //预约
    @RequestMapping(path = "/reserve", method = RequestMethod.POST)
    @ResponseBody
    public Result reserve(Integer id, HttpSession session) {//用session标记客户端
        ParkingSpace parkingSpace = (ParkingSpace) session.getAttribute("reserve");
        if (parkingSpace != null) {
            return Result.newErrResult("预约失败，您已预约了" + parkingSpace.getId() + "号车位");
        }
        System.out.println("reserve方法，请求参数id:" + id);
        if (id == null) {//不传id参数，找到一个空闲的车位
            parkingSpace = parkingSpaceService.findOneFree();
            id = parkingSpace.getId();
            if (parkingSpace == null) {
                return Result.newErrResult("预约失败，没有空闲车位");
            }
        } else {//传id参数，找到对应车位
            parkingSpace = parkingSpaceService.findById(id);
            if (parkingSpace == null) {
                return Result.newErrResult("预约失败，该车位不存在");
            }
        }

        Result result = parkingSpaceService.reserve(parkingSpace.getId());
        if (result.getFlag()) {
            //预约信息存入session
            session.setAttribute("reserve", parkingSpaceService.findById(id));
            //session.setMaxInactiveInterval(ParkingSpaceService.RESERVE_MINUTES * 60);//1分钟有效期
            sessionMap.put(id, session);
            result.setMsg("预定成功，请在" + ParkingSpaceService.RESERVE_MINUTES
                    + "分钟内停入" + parkingSpace.getId() + "号车位");
        } else {
            result.setMsg(parkingSpace.getStatus() == 2 ? "预约失败，该车位处于预定冷却状态" : "预约失败，该车位不空闲");
        }
        return result;
    }

    //客户端查看预约信息
    @RequestMapping(path = "/reserveInfo", method = RequestMethod.GET)
    @ResponseBody
    public Result getReserveInfo(HttpSession session) {
        ParkingSpace parkingSpace = (ParkingSpace) session.getAttribute("reserve");
        if (parkingSpace == null) {
            return Result.newErrResult("您没有预约车位或预约已过期");
        }
        return Result.newResult("您已预约，请尽快停入车位" + parkingSpace.getId(), parkingSpace);
    }

    //履行预约来停车
    @RequestMapping(path = "/reserveUnlock", method = RequestMethod.POST)
    @ResponseBody
    public Result reserveUnlock(HttpSession session) {
        ParkingSpace parkingSpace = (ParkingSpace) session.getAttribute("reserve");
        if (parkingSpace == null) {
            return Result.newErrResult("解锁失败，您没有预约车位或预约已过期");
        }

        session.removeAttribute("reserve");//去掉session预定信息
        Integer id = parkingSpace.getId();
        sessionMap.remove(id);

        Result result = parkingSpaceService.reserveUnlock(id);
        result.setMsg("预定车位已解锁，请立即停入" + id + "号车位");
        return result;
    }

}
